package com.wonders.auth.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wondersgroup.bigdata.questionnaire.po.sys.MenuPO;
import com.wondersgroup.bigdata.questionnaire.po.sys.RolePO;
import com.wondersgroup.bigdata.questionnaire.po.sys.UserPO;
import com.wondersgroup.bigdata.questionnaire.service.sys.MenuService;
import com.wondersgroup.bigdata.questionnaire.service.sys.RoleService;
import com.wondersgroup.bigdata.questionnaire.service.sys.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author wonders
 */
public class ShiroRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;


    @Resource
    private MenuService menuService;

    /**
     * 登录认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();
        List<UserPO> userPOList = userService.list(new QueryWrapper<UserPO>().eq("name", userName));
        if (userPOList.isEmpty()) {
            return null;
        }
        UserPO userPO = userPOList.get(0);
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                userPO,
                userPO.getPassword(),
                ByteSource.Util.bytes(userPO.getSalt()),
                getName()
        );
        return simpleAuthenticationInfo;
    }

    /**
     * 权限认证
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        UserPO userPO = (UserPO) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        List<RolePO> rolePOList = roleService.getRolesByUser(userPO.getId());
        for (RolePO role : rolePOList) {
            List<MenuPO> menuPOList = menuService.getPermissionByRole(role.getId());
            simpleAuthorizationInfo.addRole(role.getRemarks());
            for (MenuPO menuPO : menuPOList) {
                simpleAuthorizationInfo.addStringPermission(menuPO.getPermission());
            }
        }
        return simpleAuthorizationInfo;
    }


}
